/*
 * @Descripttion: 文件管理
 * @version:
 * @Author: lfzxs@qq.com
 * @Date: 2022-09-27 14:25:29
 * @LastEditors: lfzxs@qq.com
 * @LastEditTime: 2022-10-25 13:50:57
 */
package base

import (
	"errors"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
)

var (
	HttpFileMrgKit = httpFileMrgKit{}
	// 文件管理器链表
	httpFilerMrgList map[string]IHttpFile
)

// Http文件操作接口
type IHttpFile interface {
	//写入文件
	WriteUploadFile(path string, file *ghttp.UploadFile, fileType string) (writeSize int64, err error)

	//追加文件
	// AppendFile(path string, file *ghttp.UploadFile, start int64) (writeSize int64, err error)

	//读取文件
	ReadFile(path string) (data []byte, err error)

	//
	// ReadFile(path string, start int64, end int64)(data []byte, err error)
}

// 文件事件
type IFileEvent interface {
}

type httpFileMrgKit struct {
	// 默认
	defmrg IHttpFile
}

func (mrg *httpFileMrgKit) SetDef(fileMrg IHttpFile) {
	mrg.defmrg = fileMrg
}

func (mrg *httpFileMrgKit) GetDef() IHttpFile {
	return mrg.defmrg
}

// 注册
func (mrg *httpFileMrgKit) Regist(name string, fileMrg IHttpFile) error {

	_, ok := mrg.Get(name)
	if ok {
		err := gerror.NewCode(gcode.CodeOperationFailed, "字典已存在")

		return err
	}

	httpFilerMrgList[name] = fileMrg

	if mrg.defmrg == nil {
		mrg.defmrg = fileMrg
	}

	return nil
}

// 注销
func (mrg *httpFileMrgKit) UnRegist(name string) error {
	delete(httpFilerMrgList, name)

	return nil
}

// 获取管理器
func (mrg *httpFileMrgKit) Get(name string) (IHttpFile, bool) {
	val, ok := httpFilerMrgList[name]
	return val, ok
}

func (mrg *httpFileMrgKit) WriteFile(path string, file *ghttp.UploadFile, fileType string) (writeSize int64, err error) {
	if mrg.GetDef() == nil {
		return 0, errors.New("default Filemrg is null")
	}
	return mrg.GetDef().WriteUploadFile(path, file, fileType)
}

// func (mrg *httpFileMrgKit) AppendFile(path string, file *ghttp.UploadFile, start int64) (writeSize int64, err error) {
// 	if mrg.GetDef() == nil {
// 		return 0, errors.New("default Filemrg is null")
// 	}
// 	return mrg.GetDef().AppendFile(path, file, start)
// }

func (mrg *httpFileMrgKit) ReadFile(path string) (data []byte, err error) {
	if mrg.GetDef() == nil {
		return nil, errors.New("default Filemrg is null")
	}
	return mrg.GetDef().ReadFile(path)
}
